package com.yztc.xiami_app.ui.user.model;

import com.yztc.xiami_app.bean.user.MyUser;
import com.yztc.xiami_app.ui.user.interfaces.IUserRegisterListener;

import java.io.File;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * Created by 周旭 on 2016/12/4.
 */

public class UserModelImpl implements IUserModel {
    @Override
    public void register(String userName, String password, String email,String phone, BmobFile userHeaderFile, final IUserRegisterListener listener) {
        MyUser myUser = new MyUser();
        myUser.setUsername(userName); //设置用户名
        myUser.setPassword(password); //设置密码
        if(email != null){
            myUser.setEmail(email); //设置邮箱
        }
        myUser.setMobilePhoneNumber(phone); //设置手机号码
        if(userHeaderFile != null){
            myUser.setHeaderPic(userHeaderFile); //设置头像的图片
        }


        //注册
        myUser.signUp(new SaveListener<MyUser>() {
            @Override
            public void done(MyUser s, BmobException e) {
                if (e == null) {
                    //注册成功
                    listener.getResult(true,0);
                } else {
                    //Log.i("tag","------->注册失败"+e.getMessage()+"\n"+e.getCause()+e.getErrorCode()+e.getStackTrace().toString());
                    /**注册失败,第二个参数为错误码，其中
                     * 202：用户名已存在
                     * 203：邮箱已存在
                     */
                    listener.getResult(false,e.getErrorCode());
                }
            }
        });
    }

    @Override
    public void saveHeaderPic(String headerPicPath,final IUserRegisterListener listener) {
        //把图片保存到Bmob云的文件管理
        final BmobFile bmobFile = new BmobFile(new File(headerPicPath));
        bmobFile.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if(e == null){
                    //上传头像成功
                    listener.uploadSuccess(bmobFile);

                }else {
                    //上传头像失败
                    listener.uploadFailure();
                }
            }
        });
    }
}
